package com.xyht.sca_s.student_manage_system.common.aliyunImg;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.facebody20191230.Client;
import com.aliyun.tea.TeaException;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.xyht.sca_s.student_manage_system.common.aliyunImg.entity.resp.CompareFaceResp;
import com.xyht.sca_s.student_manage_system.common.aliyunImg.entity.resp.RecognizeFaceOriginResp;
import com.xyht.sca_s.student_manage_system.common.aliyunImg.entity.resp.RecognizeFaceResp;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.xyht.sca_s.student_manage_system.common.aliyunImg.constant.AliyunImgConstant.QUALITY_SCORE_THRESHOLD;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.commonConstant.ACCESS_KEY_ID;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.commonConstant.SECRET;

@Component
@Log4j2
public class AliyunImgUtil {

    public static Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(ACCESS_KEY_ID)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(SECRET);
        config.endpoint = "facebody.cn-shanghai.aliyuncs.com";
        return new Client(config);
    }

    public static com.aliyun.teaopenapi.models.Params createApiInfo(String action_name) throws Exception {
        com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
                // 接口名称
                .setAction(action_name)
                // 接口版本
                .setVersion("2019-12-30")
                // 接口协议
                .setProtocol("HTTPS")
                // 接口 HTTP 方法
                .setMethod("POST")
                .setAuthType("AK")
                .setStyle("RPC")
                // 接口 PATH
                .setPathname("/")
                // 接口请求体内容格式
                .setReqBodyType("formData")
                // 接口响应体内容格式
                .setBodyType("json");
        return params;
    }


    /**
     * 人脸比对
     *
     * @param url1 oss地址
     * @param url2 oss地址
     * @return
     */
    public static CompareFaceResp CompareFaceUrl(String url1, String url2) {
        CompareFaceResp compareFaceResp = new CompareFaceResp();
        try {
            com.aliyun.teaopenapi.Client client = createClient();
            com.aliyun.teaopenapi.models.Params params = createApiInfo("CompareFace");
            // body params
            java.util.Map<String, Object> body = new java.util.HashMap<>();
            body.put("QualityScoreThreshold", QUALITY_SCORE_THRESHOLD);
            body.put("ImageURLA", url1);
            body.put("ImageURLB", url2);
            // runtime options
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
                    .setBody(body);
            // 复制代码运行请自行打印 API 的返回值
            // 返回值为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
            Map<String, Object> compareFaceResponse = (Map<String, Object>) client.callApi(params, request, runtime);
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(compareFaceResponse));
            log.debug("++++++++++++++++++++++++++"+jsonObject.toJSONString());
            // 直接从Map中获取body部分
            Gson gson = new Gson();
            JsonObject bodyJson = gson.fromJson(new Gson().toJson(compareFaceResponse.get("body")), JsonObject.class);
            JsonObject dataJson = bodyJson.getAsJsonObject("Data");
            compareFaceResp.setConfidence(dataJson.get("Confidence").getAsFloat());
            compareFaceResp.setQualityScoreA(dataJson.get("QualityScoreA").getAsFloat());
            compareFaceResp.setQualityScoreB(dataJson.get("QualityScoreB").getAsFloat());
            return compareFaceResp;
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }

    /**
     * 人脸比对
     *
     * @param imgData1  base64编码
     * @param imgData2  base64编码
     * @return
     */
    public static CompareFaceResp compareFaceImgData(String imgData1, String imgData2) {
        CompareFaceResp compareFaceResp = new CompareFaceResp();
        try {
            com.aliyun.teaopenapi.Client client = createClient();
            com.aliyun.teaopenapi.models.Params params = createApiInfo("CompareFace");
            // body params
            java.util.Map<String, Object> body = new java.util.HashMap<>();
            body.put("QualityScoreThreshold", QUALITY_SCORE_THRESHOLD);
            body.put("ImageDateA", imgData1);
            body.put("ImageDateB", imgData2);
            // runtime options
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
                    .setBody(body);
            // 复制代码运行请自行打印 API 的返回值
            // 返回值为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
            Map<String, Object> compareFaceResponse = (Map<String, Object>) client.callApi(params, request, runtime);
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(compareFaceResponse));
            log.debug("++++++++++++++++++++++++++"+jsonObject.toJSONString());
            // 直接从Map中获取body部分
            Gson gson = new Gson();
            JsonObject bodyJson = gson.fromJson(new Gson().toJson(compareFaceResponse.get("body")), JsonObject.class);
            JsonObject dataJson = bodyJson.getAsJsonObject("Data");
            compareFaceResp.setConfidence(dataJson.get("Confidence").getAsFloat());
            compareFaceResp.setQualityScoreA(dataJson.get("QualityScoreA").getAsFloat());
            compareFaceResp.setQualityScoreB(dataJson.get("QualityScoreB").getAsFloat());
            return compareFaceResp;
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }

    /**
     * 人脸属性识别
     *
     * @param imgUrl  oss地址
     * @return
     */
    public static RecognizeFaceResp recognizeFace(String imgUrl) {
        RecognizeFaceResp recognizeFaceResp = new RecognizeFaceResp();
        try {
            com.aliyun.teaopenapi.Client client = createClient();
            com.aliyun.teaopenapi.models.Params params = createApiInfo("RecognizeFace");
            // body params
            java.util.Map<String, Object> body = new java.util.HashMap<>();
            body.put("ImageType", null);
            body.put("ImageURL", imgUrl);
            body.put("Age", null);     //人脸年龄结果
            body.put("Gender", null);  //人脸性别结果
            body.put("Hat", true);     //检测是否戴帽子
            body.put("Glass", true);   //检测是否戴眼镜
            body.put("Beauty", null);  //人脸美丑程度
            body.put("Expression", null);  //人脸表情
            body.put("Mask", true);    //检测是否戴口罩
            body.put("Quality", true);  //人脸质量
            body.put("MaxFaceNumber", 1); //最多检测人脸数量
            // runtime options
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
                    .setBody(body);
            // 复制代码运行请自行打印 API 的返回值
            // 返回值为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
            Map<String, Object> compareFaceResponse = (Map<String, Object>) client.callApi(params, request, runtime);
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(compareFaceResponse));
            log.debug("++++++++++++++++++++++++++"+jsonObject.toJSONString());
            // 直接从Map中获取body部分
            Gson gson = new Gson();
            JsonObject bodyJson = gson.fromJson(new Gson().toJson(compareFaceResponse.get("body")), JsonObject.class);
            JsonObject dataJson = bodyJson.getAsJsonObject("Data");
            RecognizeFaceOriginResp originResp = JSONObject.parseObject(dataJson.toString(), RecognizeFaceOriginResp.class);
            BeanUtils.copyProperties(originResp,recognizeFaceResp);

            recognizeFaceResp.setScoreQualities(originResp.getQualities().getScoreList().get(0));
            recognizeFaceResp.setFnfQualities(originResp.getQualities().getFnfList().get(0));
            recognizeFaceResp.setBlurQualities(originResp.getQualities().getBlurList().get(0));
            recognizeFaceResp.setIlluQualities(originResp.getQualities().getIlluList().get(0));
            recognizeFaceResp.setMaskQualities(originResp.getQualities().getMaskList().get(0));
            recognizeFaceResp.setNoiseQualities(originResp.getQualities().getNoiseList().get(0));
            recognizeFaceResp.setGlassQualities(originResp.getQualities().getGlassList().get(0));
            recognizeFaceResp.setPoseQualities(originResp.getQualities().getPoseList().get(0));
            recognizeFaceResp.setIsHat(originResp.getHatList().get(0));
            recognizeFaceResp.setIsGlasses(originResp.getGlasses().get(0));
            recognizeFaceResp.setIsMasks(originResp.getMasks().get(0));
            return recognizeFaceResp;
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }


}
